import {prop} from './prop';

export function sort(list, propSpec) {

  if (propSpec === undefined) {
    throw Error('sort: propSpec not provided')
  }

  list.sort((prev, next) => {
    const prevVal = prop(prev, propSpec);
    const nextVal = prop(next, propSpec);

    return prevVal > nextVal ? 1 : prevVal < nextVal ? -1 : 0
  })

  return list;
}

export function grip(list, propSpec){

  let group = {};

  if (propSpec === undefined) {
    throw Error('grip: propSpec not provided')
  }  

  for (let i = 0; i < list.length; i++){
    const rec = list[i];
    const label = prop(rec, propSpec);

    group[label] ??= [];
    group[label].push(rec);
  }

  return group;
}

export function part(list, size) {
  
  const newList = [];
  
  for (let i = Math.floor(list.length / size); i--> 0; ) {
    newList[i] = list.slice(i*size, (i+1)*size);
  }
  
  return newList;
}

export function merge(destMap, fromMap, mergeFunc) {

  for (const [fromKey, from] of Object.entries(fromMap)) {
    const dest = destMap[fromKey];
    dest && mergeFunc(dest, from);
  }

}

export function map(dict, func) {
  return Object.fromEntries(Object.entries(dict).map(func));
}

export function grap(dict, func = ([, v]) => v) {
  return Object.entries(dict).map(func);
}
